<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { getOwnerController, getBuildingController, getHouseController } from '@/api-client'
import type {
  OwnerVO,
  OwnerQueryRequest,
  Owner,
  Building,
  HouseVO,
} from '@/api-client'

interface OwnerFormModel {
  id?: number
  userName: string
  tel: string
  sex: string
  identity: string
  remarks: string
  buildingId?: number
  houseId?: number
}

const ownerApi = getOwnerController()
const buildingApi = getBuildingController()
const houseApi = getHouseController()

const loading = ref(false)
const submitLoading = ref(false)
const ownerList = ref<OwnerVO[]>([])
const total = ref(0)
const selectedOwners = ref<OwnerVO[]>([])
const buildingOptions = ref<Building[]>([])
const searchHouseOptions = ref<HouseVO[]>([])
const formHouseOptions = ref<HouseVO[]>([])

const searchForm = reactive<OwnerQueryRequest>({
  current: 1,
  pageSize: 10,
  userName: '',
  tel: '',
  identity: '',
  sex: undefined,
  buildingId: undefined,
  houseId: undefined,
})

const createEmptyOwnerForm = (): OwnerFormModel => ({
  id: undefined,
  userName: '',
  tel: '',
  sex: '男',
  identity: '',
  remarks: '',
  buildingId: undefined,
  houseId: undefined,
})

const ownerForm = reactive<OwnerFormModel>(createEmptyOwnerForm())
const ownerFormRef = ref<FormInstance>()
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => (isEdit.value ? '编辑业主' : '新增业主'))

const phonePattern = /^1[3-9]\d{9}$/
const identityPattern = /(^\d{15}$)|(^\d{17}([0-9Xx])$)/

const rules = reactive<FormRules<OwnerFormModel>>({
  userName: [{ required: true, message: '请输入业主姓名', trigger: 'blur' }],
  tel: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: phonePattern, message: '手机号格式不正确', trigger: 'blur' },
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  identity: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: identityPattern, message: '身份证号码格式不正确', trigger: 'blur' },
  ],
  buildingId: [{ required: true, message: '请选择所属楼栋', trigger: 'change' }],
  houseId: [{ required: true, message: '请选择关联房屋', trigger: 'change' }],
  remarks: [{ max: 200, message: '备注不能超过200个字符', trigger: 'blur' }],
})

const sexOptions = [
  { label: '男', value: '男' },
  { label: '女', value: '女' },
]

// 缓存楼栋下的房屋列表，避免重复请求
const houseCache = new Map<number, HouseVO[]>()

const fetchOwnerList = async () => {
  loading.value = true
  try {
    const response = await ownerApi.listOwner({ ...searchForm })
    if (response.code === 200 && response.data) {
      ownerList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取业主列表失败')
    }
  } catch (error) {
    console.error('fetchOwnerList error:', error)
    ElMessage.error('获取业主列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchBuildingList = async () => {
  try {
    const response = await buildingApi.getAllBuildings()
    if (response.code === 200) {
      buildingOptions.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取楼栋信息失败')
    }
  } catch (error) {
    console.error('fetchBuildingList error:', error)
    ElMessage.error('获取楼栋信息失败，请稍后重试')
  }
}

const loadHousesByBuilding = async (buildingId: number): Promise<HouseVO[]> => {
  if (houseCache.has(buildingId)) {
    return [...(houseCache.get(buildingId) || [])]
  }
  try {
    const response = await houseApi.getHousesByBuildingId(buildingId)
    if (response.code === 200) {
      const list = response.data || []
      houseCache.set(buildingId, list)
      return [...list]
    }
    ElMessage.error(response.message || '获取房屋列表失败')
  } catch (error) {
    console.error('loadHousesByBuilding error:', error)
    ElMessage.error('获取房屋列表失败，请稍后重试')
  }
  return []
}

const resetForm = () => {
  Object.assign(ownerForm, createEmptyOwnerForm())
  formHouseOptions.value = []
  ownerFormRef.value?.clearValidate()
}

const handleSearch = () => {
  searchForm.current = 1
  fetchOwnerList()
}

const handleReset = () => {
  searchForm.userName = ''
  searchForm.tel = ''
  searchForm.identity = ''
  searchForm.sex = undefined
  searchForm.buildingId = undefined
  searchForm.houseId = undefined
  searchHouseOptions.value = []
  handleSearch()
}

const handleSizeChange = (pageSize: number) => {
  searchForm.pageSize = pageSize
  searchForm.current = 1
  fetchOwnerList()
}

const handleCurrentChange = (page: number) => {
  searchForm.current = page
  fetchOwnerList()
}

const handleSelectionChange = (selection: OwnerVO[]) => {
  selectedOwners.value = selection
}

const handleSearchBuildingChange = async (buildingId?: number) => {
  searchForm.houseId = undefined
  if (!buildingId) {
    searchHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  searchHouseOptions.value = houses
}

const handleSearchBuildingClear = () => {
  searchForm.buildingId = undefined
  handleSearchBuildingChange()
}

const handleFormBuildingChange = async (buildingId?: number) => {
  ownerForm.houseId = undefined
  if (!buildingId) {
    formHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  formHouseOptions.value = houses
}

const handleFormBuildingClear = () => {
  ownerForm.buildingId = undefined
  handleFormBuildingChange()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
  nextTick(() => ownerFormRef.value?.clearValidate())
}

const handleEdit = async (row: OwnerVO) => {
  if (!row.id) {
    ElMessage.error('未获取到业主ID，无法编辑')
    return
  }
  isEdit.value = true
  resetForm()
  ownerForm.id = row.id
  ownerForm.userName = row.userName || ''
  ownerForm.tel = row.tel || ''
  ownerForm.sex = row.sex || '男'
  ownerForm.identity = row.identity || ''
  ownerForm.remarks = row.remarks || ''

  const buildingId = row.houseVO?.building?.id
  if (buildingId) {
    ownerForm.buildingId = buildingId
    formHouseOptions.value = await loadHousesByBuilding(buildingId)
  }
  ownerForm.houseId = row.houseVO?.id

  dialogVisible.value = true
  nextTick(() => ownerFormRef.value?.clearValidate())
}

const handleDelete = (row: OwnerVO) => {
  if (!row.id) {
    ElMessage.error('未获取到业主ID，无法删除')
    return
  }
  ElMessageBox.confirm(`确定要删除业主【${row.userName || ''}】吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const response = await ownerApi.deleteOwner({ id: row.id as number })
      if (response.code === 200) {
        ElMessage.success('删除成功')
        await fetchOwnerList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    })
    .catch(() => {
      /* 用户取消操作 */
    })
}

const handleBatchDelete = () => {
  if (!selectedOwners.value.length) {
    ElMessage.warning('请至少选择一位业主')
    return
  }
  const ids = selectedOwners.value
    .map((item) => item.id)
    .filter((id): id is number => typeof id === 'number')

  if (!ids.length) {
    ElMessage.warning('所选业主缺少有效ID')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 位业主吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const response = await ownerApi.deleteBatch4(ids)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        await fetchOwnerList()
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    })
    .catch(() => {
      /* 用户取消操作 */
    })
}

const handleSubmit = async () => {
  if (!ownerFormRef.value) return

  await ownerFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请检查表单信息')
      return
    }

    submitLoading.value = true
    const payload: Owner = {
      id: ownerForm.id,
      userName: ownerForm.userName,
      tel: ownerForm.tel,
      sex: ownerForm.sex,
      identity: ownerForm.identity,
      remarks: ownerForm.remarks,
      houseId: ownerForm.houseId,
    }

    try {
      if (isEdit.value) {
        if (!ownerForm.id) {
          ElMessage.error('业主ID缺失，无法更新')
          return
        }
        const response = await ownerApi.updateOwner(ownerForm.id, payload)
        if (response.code === 200) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          await fetchOwnerList()
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } else {
        const response = await ownerApi.saveOwner(payload)
        if (response.code === 200) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          await fetchOwnerList()
        } else {
          ElMessage.error(response.message || '新增失败')
        }
      }
    } catch (error) {
      console.error('handleSubmit error:', error)
      ElMessage.error('提交失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const formatBuildingLabel = (building?: Building) => {
  if (!building) return '-'
  const parts = [building.numbers, building.units].filter(Boolean)
  return parts.join(' ') || '-'
}

const formatHouseLabel = (house?: HouseVO) => {
  if (!house) return '-'
  const segments: string[] = []
  if (house.storey !== undefined && house.storey !== null) {
    segments.push(`${house.storey}层`)
  }
  if (house.numbers) {
    segments.push(house.numbers)
  }
  const base = segments.join(' ')
  if (house.area) {
    return `${base || '房屋'} · ${house.area}㎡`
  }
  return base || '-'
}

const formatOwnerBuilding = (owner: OwnerVO) => formatBuildingLabel(owner.houseVO?.building)
const formatOwnerHouse = (owner: OwnerVO) => formatHouseLabel(owner.houseVO)
const formatHouseStatusType = (status?: number) => (status === 1 ? 'success' : 'info')
const formatHouseStatusText = (status?: number) => (status === 1 ? '已入住' : '空置')

onMounted(() => {
  fetchBuildingList()
  fetchOwnerList()
})
</script>

<template>
  <div class="owner-view">
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="业主姓名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入业主姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input
            v-model="searchForm.tel"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.sex"
            placeholder="请选择性别"
            clearable
            style="width: 140px"
          >
            <el-option v-for="option in sexOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证">
          <el-input
            v-model="searchForm.identity"
            placeholder="请输入身份证号码"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="楼栋">
          <el-select
            v-model="searchForm.buildingId"
            placeholder="请选择楼栋"
            clearable
            filterable
            style="width: 180px"
            @change="handleSearchBuildingChange"
            @clear="handleSearchBuildingClear"
          >
            <el-option
              v-for="building in buildingOptions"
              :key="building.id"
              :label="formatBuildingLabel(building)"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋">
          <el-select
            v-model="searchForm.houseId"
            placeholder="请选择房屋"
            clearable
            filterable
            style="width: 200px"
            :disabled="!searchForm.buildingId"
          >
            <el-option
              v-for="house in searchHouseOptions"
              :key="house.id"
              :label="formatHouseLabel(house)"
              :value="house.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="action-bar">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增业主</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="ownerList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userName" label="业主姓名" min-width="140" />
        <el-table-column prop="tel" label="联系电话" min-width="150" />
        <el-table-column label="性别" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.sex === '女' ? 'success' : 'primary'" size="small">
              {{ row.sex || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="identity" label="身份证号码" min-width="200" show-overflow-tooltip />
        <el-table-column label="楼栋" min-width="160">
          <template #default="{ row }">{{ formatOwnerBuilding(row) }}</template>
        </el-table-column>
        <el-table-column label="房屋" min-width="200">
          <template #default="{ row }">
            <div class="house-cell">
              <span>{{ formatOwnerHouse(row) }}</span>
              <el-tag
                v-if="row.houseVO?.status !== undefined"
                :type="formatHouseStatusType(row.houseVO?.status)"
                size="small"
              >
                {{ formatHouseStatusText(row.houseVO?.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" text size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        :current-page="searchForm.current"
        :page-size="searchForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="580px" @close="resetForm">
      <el-form ref="ownerFormRef" :model="ownerForm" :rules="rules" label-width="100px">
        <el-form-item label="业主姓名" prop="userName">
          <el-input v-model="ownerForm.userName" placeholder="请输入业主姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="ownerForm.tel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ownerForm.sex">
            <el-radio v-for="option in sexOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证" prop="identity">
          <el-input v-model="ownerForm.identity" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="楼栋" prop="buildingId">
          <el-select
            v-model="ownerForm.buildingId"
            placeholder="请选择楼栋"
            clearable
            filterable
            @change="handleFormBuildingChange"
            @clear="handleFormBuildingClear"
          >
            <el-option
              v-for="building in buildingOptions"
              :key="building.id"
              :label="formatBuildingLabel(building)"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋" prop="houseId">
          <el-select
            v-model="ownerForm.houseId"
            placeholder="请选择房屋"
            clearable
            filterable
            :disabled="!ownerForm.buildingId"
          >
            <el-option
              v-for="house in formHouseOptions"
              :key="house.id"
              :label="formatHouseLabel(house)"
              :value="house.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="ownerForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.owner-view {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.house-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: inline-flex;
  gap: 12px;
}
</style>
